package Controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: tangBin
 * @Date: 2022/1/5 0005 15:40
 * @Description: 模拟搜索飞机接口
 */
public class FightQueryExample {
    //定义航班
    private static List<String> fightCompany = Arrays.asList("CSA", "CEA", "HNA");

    public static void main(String[] args) {
        List<String> results = search("sh", "bj");
        System.out.printf("=============result============\n");
        results.forEach(System.out::println);
    }

    static List<String> search(String original, String dest) {
        final List<String> result = new ArrayList<>();
        List<FightQueryTask> tasks = fightCompany.stream().map(f ->
                createSearchTask(f, original, dest)).collect(Collectors.toList());
        for (Thread task : tasks) {
            task.start();
        }
        //tasks.forEach(Thread::start);
        for (Thread thread : tasks) {
            try {
                thread.join();
            } catch (InterruptedException e) {

            }

        }
       /* tasks.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {

            }
            ;
        });*/
        for (FightQueryTask task : tasks) {
            result.addAll(task.get());
        }
        System.out.printf("==result==%s", result);
        //tasks.stream().map(FightQueryTask::get).forEach(result::addAll);
        return result;
    }

    static FightQueryTask createSearchTask(String fight, String original, String dest) {
        return new FightQueryTask(fight, original, dest);
    }
}

//定义结果返回结合
interface FightQuery {
    List<String> get();
}

class FightQueryTask extends Thread implements FightQuery {
    private final String origin;
    private final String destination;
    //private final String fight;
    private final List<String> stringList = new ArrayList<>();

    FightQueryTask(String fight, String origin, String destination) {
        //this.fight = fight;
        super(fight);
        this.origin = origin;
        this.destination = destination;
    }


    @Override
    public void run() {
        System.out.printf("%s-query from %s to %s \n", getName(), origin, destination);
        int randomVal = ThreadLocalRandom.current().nextInt(10);
        try {
            TimeUnit.SECONDS.sleep(randomVal);
            this.stringList.add(getName() + "_" + randomVal);
            System.out.printf("The Fight:%s list query successful\n", getName());
        } catch (InterruptedException e) {

        }

    }

    @Override
    public List<String> get() {
        return this.stringList;
    }
}